<template>
  <div class="app-container">
    <search-box :isMulti="false">
      <template slot="content">
        <div class="left-box">
          <el-form-item label="用户姓名">
            <el-input v-model="listQuery.userName"
                      placeholder="请输入"
                      clearable/>
          </el-form-item>

          <el-form-item label="部门名称">
            <el-select v-model="listQuery.departmentName"
                       placeholder="请选择部门">
              <el-option v-for="item in departmentList"
                         :key="item.departmentName"
                         :label="item.departmentName"
                         :value="item.departmentName">
              </el-option>
            </el-select>
          </el-form-item>

        </div>
        <div class="right-box">
          <el-button size="mini"
                     @click="handleFilter">查询
          </el-button>
          <el-button size="mini"
                     @click="reset" type="info">重置
          </el-button>
          <el-button size="mini"
                     type="success" @click="handleCreate">新增
          </el-button>
        </div>
      </template>
    </search-box>
    <div class="table-wrap">
      <el-table :data="list"
                style="width:100%"
                element-loading-text="Loading"
                height="600">
        <el-table-column
          type="index"
          width="50"
          label="序号"
        ></el-table-column>
        <el-table-column prop="userCode"
                         label="工号">
        </el-table-column>

        <el-table-column prop="userName"
                         label="姓名">
        </el-table-column>
        <el-table-column prop="userAccount"
                         label="登录名">
        </el-table-column>
        <el-table-column prop="gender"
                         label="性别">
        </el-table-column>
        <el-table-column prop="age"
                         label="年龄">
        </el-table-column>
        <el-table-column prop="departmentName"
                         label="所属部门">
        </el-table-column>
        <el-table-column prop="position"
                         label="部门职务">
        </el-table-column>
        <el-table-column prop="userRank"
                         label="岗位职级">
        </el-table-column>
        <el-table-column prop="roleName"
                         label="所属权限">
        </el-table-column>

        <el-table-column label="操作" align="center" width="250" class-name="small-padding fixed-width">
          <template slot-scope="scope">
            <el-button type="primary" size="mini" @click="handleUpdate(scope.row)" >
              编辑
            </el-button>
            <el-button size="mini" type="danger" @click="handleDelete(scope.row)">
              删除
            </el-button>
          </template>
        </el-table-column>

      </el-table>
      <pagination v-show="total>0"
                  :total="total"
                  :page.sync="listQuery.pageNumber"
                  :limit.sync="listQuery.pageSize"
                  @pagination="getList"/>
    </div>

    <el-dialog
      :title="dialogTitle"
      :visible.sync="dialogVisible"
      width="30%">
      <el-form ref="form" :rules="rules" :model="listQuery" label-width="80px">

        <el-form-item label="工号" prop="userCode">
          <el-input v-model="listQuery.userCode" ></el-input>
        </el-form-item>
        <el-form-item label="姓名" prop="userName">
          <el-input v-model="listQuery.userName" ></el-input>
        </el-form-item>
        <el-form-item label="用户名" prop="userAccount" v-if="this.dialogTitle=='用户新增'">
          <el-input v-model="listQuery.userAccount" ></el-input>
          <span style="color: #999999;font-size: 12px">
            该用户名为新增用户的登录名，密码与用户名相同
          </span>
        </el-form-item>

        <el-form-item label="性别" prop="gender">
          <el-select v-model="listQuery.gender"
                     placeholder="请选择性别">
            <el-option v-for="item in genderList"
                       :key="item.label"
                       :label="item.label"
                       :value="item.label">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="出生日期" prop="birth">
          <el-date-picker type="date" placeholder="选择日期" v-model="listQuery.birth" style="width: 100%;"></el-date-picker>
        </el-form-item>
        <el-form-item label="身份证号" prop="idCard">
          <el-input v-model="listQuery.idCard" ></el-input>
        </el-form-item>
        <el-form-item label="所属部门" prop="departmentName">
            <el-select v-model="listQuery.departmentName" @change="getPositionList"
                       placeholder="请选择部门">
              <el-option v-for="item in departmentList"
                         :key="item.departmentName"
                         :label="item.departmentName"
                         :value="item.departmentName">
              </el-option>
            </el-select>

        </el-form-item>
        <el-form-item label="部门职务" prop="position">
<!--          <el-input v-model="listQuery.position" ></el-input>-->
          <el-select v-model="listQuery.position"
                     placeholder="请选择职务" >
            <el-option v-for="item in positionList"
                       :key="item.positionName"
                       :label="item.positionName"
                       :value="item.positionName">
            </el-option>
          </el-select>

        </el-form-item>
        <el-form-item label="岗位职级" prop="position">

          <el-select v-model="listQuery.userRank"
                     placeholder="请选择岗位职级">
            <el-option v-for="item in rankList"
                       :key="item.postName+'（'+item.rankName+'）'"
                       :label="item.postName+'（'+item.rankName+'）'"
                       :value="item.postName+'（'+item.rankName+'）'">
            </el-option>
          </el-select>

        </el-form-item>
        <el-form-item label="所属权限" prop="roleName">
          <el-select v-model="listQuery.roleName"
                     placeholder="请选择权限">
            <el-option v-for="item in rulesList"
                       :key="item.roleName"
                       :label="item.roleName"
                       :value="item.roleName">
            </el-option>
          </el-select>
        </el-form-item>

      </el-form>
      <span slot="footer" class="dialog-footer">
    <el-button @click="cancel">取 消</el-button>
    <el-button type="primary" @click="onSubmit" >确 定</el-button>
  </span>
    </el-dialog>


  </div>
</template>

<script>
  import { mapGetters } from 'vuex'
  import * as apiUser from '@/api/user'
  import * as department from '@/api/system-setting/department'
  import * as user from '@/api/system-setting/user'
  import * as rank from '@/api/system-setting/rank'
  import waves from '@/directive/waves' // waves directive
  import Pagination from '@/components/Pagination' // secondary package based on el-pagination
  // 当然你也可以为了方便使用，将它注册到全局
  import { MessageBox } from 'element-ui'
  import bus from '@/utils/eventBus'
  import searchBox from '@/components/searchBox.vue'
  import * as position from '@/api/system-setting/position'
  export default {
    name: 'user',
    components: { Pagination, searchBox },
    directives: { waves },
    filters: {},
    data() {
      return {
        list: null,
        total: 0,
        dialogVisible: false,
        listQuery: { // 查询列表时的参数对象
          pageNumber: 1,
          departmentName: '',
          departmentCode: '',
          roleName: '',
          pageSize: 50,
          name: undefined,
          appName: process.env.VUE_APP_APP_NAME,
          tenantIdList: []
        },
        dialogTitle: '',
        rulesList: [
        ],
        departmentList: [
        ],
        rankList: [
        ],
        positionList: [
        ],
        genderList: [
          {label:'男',value:'男'},
          {label:'女',value:'女'},
          {label:'其他',value:'其他'},
        ],
        rules: {
          departmentName: [{ required: true, message: '部门名称必填', trigger: 'blur' }],
          gender: [{ required: true, message: '性别必选', trigger: 'blur' }],
          roleName: [{ required: true, message: '权限必选', trigger: 'blur' }],
          userCode: [{ required: true, message: '工号不能为空', trigger: 'blur' }],
          userName: [{ required: true, message: '姓名不能为空', trigger: 'blur' }],
          birth: [{ required: true, message: '出生日期必选', trigger: 'blur' }],
          idCard: [{ required: true, message: '身份证号不能为空', trigger: 'blur' }],
          position: [{ required: true, message: '职务不能为空', trigger: 'blur' }],
          userAccount: [{ required: true, message: '用户名不能为空', trigger: 'blur' }],
        }
      }
    },
    computed: {
      ...mapGetters([
        'selectedTenantId',
        'tenantList'
      ])
    },
    created() {
      this.getList()
      this.getDepartmentList()
      this.getRoleList()
      this.getPostList()
      // 监听 租户改变的事件,选择不同租户后,立马刷新数据
      bus.$on('selectedTenantIdChanged', () => {
        console.log('selectedTenantIdChanged事件触发...')
        this.getList()
      })

    },
    mounted() {
      // 测试用
      // var that = this
      // setTimeout(function() {
      //   that.dialogFormVisible = true
      // }, 5000)

      // alert(this.$store.getters.selectedTenantId);
    },
    beforeDestroy() { // 当路由切换到其他页面时触发
      bus.$off('selectedTenantIdChanged')
    },
    methods: {
      async getList() { // 获取列表数据
        this.listQuery.tenantIdList = []
        if (this.selectedTenantId == undefined) {//当前选中所有的租户
          this.tenantList.forEach((tenant, index) => {
            this.listQuery.tenantIdList.push(tenant.id)
          })
        } else {
          this.listQuery.tenantIdList.push(this.selectedTenantId)
        }
        const { content } = await user.getUserList(this.listQuery)
        this.list = content.list
        let date = new Date();
         let  year = date .getFullYear();
        for(let i = 0 ; i<this.list.length;i++){
          let yearBir = this.list[i].birth.substring(0,4);
          this.$set(this.list[i], 'age', year-yearBir);
        }
        this.total = content.totalCounts
      },

      async getDepartmentList() { // 获取列表数据

        const { content } = await department.getDepartmentList(this.listQuery)
        this.departmentList = content.list;

      },


      async getPostList() { // 获取列表数据
        const { content } = await rank.getRankList(this.listQuery)
        this.rankList = content.list;
      },


      async getPositionList() { // 获取列表数据
        this.positionList = []
        this.listQuery.position = ''
        const { content } = await position.getPositionList(this.listQuery)
        this.positionList = content.list

      },
      async getRoleList() { // 获取列表数据

        const { content } = await department.getRoleList(this.listQuery)
        this.rulesList = content.list;

      },
      handleFilter() {
        this.listQuery.pageNumber = 1
        this.getList()
      },

      handleCreate() {
        this.dialogVisible = true
        this.dialogTitle = '用户新增'
        this.listQuery = {};
        // this.getPositionList()
      },
      handleUpdate(row) {
        this.dialogVisible = true
        this.dialogTitle = '用户编辑'
        this.listQuery = row;
        // this.getPositionList()

      },

      handleDelete(row) {
        this.$confirm('是否删除?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          user.deleteUser(row.id).then(() => {
            this.dialogFormVisible = false
            this.$notify({
              title: '成功',
              message: '删除成功',
              type: 'success',
              duration: 2000
            })
            this.getList()
          })
        }).catch(() => {
        })

      },

      reset() {
        this.listQuery.userName = ''
        this.listQuery.departmentName = ''
        this.getList()
      },
      cancel() {
        this.listQuery.userName = ''
        this.listQuery.departmentName = ''
        this.dialogVisible = false;
        this.getList()
      },
      onSubmit(){
        this.$refs['form'].validate((valid) => {
          if (valid) {
            this.listQuery.tenantId = this.$store.getters.selectedTenantId
            if(this.dialogTitle=='用户新增'){
              user.createUser(this.listQuery).then((res) => {
                console.log(res);
                if(res.status==200){
                  if(res.content!=null){
                    this.$notify({
                      title: '成功',
                      message: '添加成功',
                      type: 'success',
                      duration: 2000
                    });
                    this.listQuery.userName = ''
                    this.listQuery.departmentName = ''
                    this.dialogVisible = false
                    this.getList();
                  }else{
                    this.$notify({
                      title: '失败',
                      message: '用户名已经被占用！',
                      type: 'error',
                      duration: 2000
                    });
                  }


                }
              })
            }else if(this.dialogTitle=='用户编辑'){
              user.updateUser(this.listQuery).then((res) => {
                console.log(res);
                if(res.status==200){
                  this.$notify({
                    title: '成功',
                    message: '修改成功',
                    type: 'success',
                    duration: 2000
                  });
                  this.listQuery.userName = ''
                  this.listQuery.departmentName = ''
                  this.dialogVisible = false
                  this.getList();

                }
              })
            }

          } else {
            console.log('error submit!!');
            return false;
          }
        });

      }



    }
  }
</script>

<style scoped>
  .app-select {
    margin-bottom: 20px;
  }
</style>
